//
//  YBSelectPeopleOrganizationView.m
//  GongXinDangJian
//
//  Created by apple on 17/11/30.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YBSelectPeopleOrganizationView.h"
#import "YBSelectPeopleNormalTableViewCell.h"
#define CELLID @"YBSelectPeopleNormalTableViewCell"

#import "YBSelectPeopleHeadView.h"
#define HEADER @"YBSelectPeopleHeadView"

#import "YBSelectShareSingalData.h"

#import "YBAddPeopleSignalData.h"

#import "YBSelectDeptListTableViewCell.h"
#define DEPTID @"YBSelectDeptListTableViewCell"


@interface YBSelectPeopleOrganizationView ()<UITableViewDelegate , UITableViewDataSource , YBSelectPeopleHeadViewDelegate>
@property (nonatomic , strong) NSArray * mainUserArray;

@property (nonatomic , strong) NSArray * mainDeptArray;

@property (nonatomic , strong) UIScrollView * titleScrollView;

@property (nonatomic , strong) UITableView * tableView;

@property (nonatomic , assign) BOOL isKVO;

@property (nonatomic , strong) YBSelectShareSingalData * myDataSource;

@property (nonatomic , strong) YBAddPeopleSignalData * addPeopleDataSource;

@property (nonatomic , strong) NSMutableArray * selectHeadArray;

@property (nonatomic , strong) NSMutableArray<UIButton *> * headButtonArray;

@end

@implementation YBSelectPeopleOrganizationView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.mainUserArray = @[];
        self.mainDeptArray = @[];
        [self ybInitMyView];
        [self addObserver:self forKeyPath:@"ybSelectChange" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
        self.isKVO = YES;
    }
    return self;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(ybSelectPeopleOrganizationViewSelectedArrayDidChange)]) {
        [self.delegate ybSelectPeopleOrganizationViewSelectedArrayDidChange];
    }
}
-(void)ybCleanObserver{
    if (self.isKVO) {
        [self removeObserver:self forKeyPath:@"ybSelectChange" context:nil];
        self.isKVO = NO;
    }
}

-(void)removeFromSuperview{
    if (self.isKVO) {
        [self removeObserver:self forKeyPath:@"ybSelectChange" context:nil];
        self.isKVO = NO;
    }
    [super removeFromSuperview];
}

-(void)setYbIsHidden:(BOOL)ybIsHidden
{
    _ybIsHidden = ybIsHidden;
    self.hidden = ybIsHidden;
}


-(void)ybInitMyView{
    [self addSubview:self.titleScrollView];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, ItemHeight * 80 - 1, [UIScreen zj_screenWith], 1)];
    lineView.backgroundColor = [UIColor themeGrayColor];
    [self addSubview:lineView];
    
    [self addSubview:self.tableView];
    
    
}




-(void)addHeadButtonWithHeadModel:(YBSelectHeadModel *)headModel{
    for (UIButton * tempButton in self.headButtonArray) {
        [tempButton setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
    }
    
    
    CGFloat buttonWidth = [headModel.NAME boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, ItemHeight * 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : LYPFONT(16)} context:nil].size.width;
    
    CGFloat beginX = 0.f;
    if (self.headButtonArray.count > 0) {
        beginX = CGRectGetMaxX(self.headButtonArray.lastObject.frame);
    }
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(beginX, 0, buttonWidth + ItemWidth * 60, ItemHeight * 80)];
    [button setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
    button.titleLabel.font = LYPFONT(16);
    [button setTitle:[ToolClass returnNoNullStringWithString:headModel.NAME] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"jiantou_r"] forState:UIControlStateNormal];
    button.tag = 300 + self.headButtonArray.count;
    
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -ItemWidth * 44, 0, ItemWidth * 44)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, buttonWidth, 0, -buttonWidth)];
    
    [button addTarget:self action:@selector(option_titleButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleScrollView addSubview:button];
    [self.headButtonArray addObject:button];
    [self.selectHeadArray addObject:headModel];
    [self.titleScrollView setupAutoContentSizeWithRightView:self.headButtonArray.lastObject rightMargin:ItemWidth * 5];
}


-(void)option_titleButton:(UIButton *)sender{
    if ([sender isEqual:self.headButtonArray.lastObject]) {
        return;
    }
    NSInteger index = sender.tag - 300;
    NSInteger totalCount = self.selectHeadArray.count - 1;
    for (NSInteger i = index + 1; i < self.selectHeadArray.count; i ++) {
        UIButton * button = self.headButtonArray[totalCount];
        [self.headButtonArray removeObject:button];
        [button removeFromSuperview];
        totalCount --;
    }
    self.selectHeadArray = [[self.selectHeadArray subarrayWithRange:NSMakeRange(0, index + 1)] mutableCopy];
    
    [self.titleScrollView setupAutoContentSizeWithRightView:self.headButtonArray.lastObject rightMargin:ItemWidth * 5];
    
    [self ybRestructureDataSourceWithModel:self.selectHeadArray.lastObject];
    
    [self.headButtonArray.lastObject setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ItemHeight * 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBSelectPeopleTotalModel * model = self.dataArray[indexPath.row];
    if ([model.DATA_TYPE integerValue] == 0) {
        YBSelectDeptListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:DEPTID forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataArray[indexPath.row];
        return cell;
    }
    else{
        YBSelectPeopleNormalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CELLID forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataArray[indexPath.row];
        cell.isOrg = YES;
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBSelectPeopleTotalModel * model = self.dataArray[indexPath.row];
    if ([model.DATA_TYPE integerValue] == 0) {
        YBSelectHeadModel * tempModel = self.dataArray[indexPath.row];
        [self addHeadButtonWithHeadModel:tempModel];
        [self ybRestructureDataSourceWithModel:tempModel];
    }
    else{
        YBPeopleInfoModel * model = self.dataArray[indexPath.row];
        model.ISSELECT = !model.ISSELECT;
        YBSelectPeopleNormalTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.cellSelected = !cell.cellSelected;
        if (self.headArray.count > 0) {
            [self judgeIsSelectAllWithSection:indexPath.section];
        }
        if (model.ISSELECT) {
            if (self.isAddPeople) {
                [self.addPeopleDataSource ybAddObjectToArrayWithModel:model];
            }
            else{
                [self.myDataSource ybAddObjectToArrayWithModel:model];
            }
        }
        else{
            if (self.isAddPeople) {
                [self.addPeopleDataSource ybRemoveObjectFromArrayWithModel:model];
            }
            else{
                [self.myDataSource ybRemoveObjectFromArrayWithModel:model];
            }
        }
        [self mySelectArrayChanged];
    }
}


-(void)judgeIsSelectAllWithSection:(NSInteger)section{
    BOOL headIsSelectAll = NO;
    NSInteger selectCount = 0;
    NSArray * tempArray = [self.dataArray copy];
    for (YBPeopleInfoModel * model in tempArray) {
        if (model.ISSELECT) {
            selectCount ++;
        }
    }
    if (tempArray.count == selectCount) {
        headIsSelectAll = YES;
    }
    YBSelectPeopleHeadView * headerView = (YBSelectPeopleHeadView *)[self.tableView headerViewForSection:section];
    headerView.viewSelected = headIsSelectAll;
    ((YBSelectHeadModel *)(self.headArray[section])).ISALLSELECT = headIsSelectAll;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.headArray.count == 0) {
        return 0.01;
    }
    return ItemHeight * 80;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.headArray.count > 0) {
        YBSelectPeopleHeadView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HEADER];
        headerView.ybSection = section;
        headerView.model = self.headArray[section];
        headerView.delegate = self;
        headerView.isOrg = YES;
        return headerView;
    }
    else{
        return nil;
    }
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}


-(void)viewDidClickWithSection:(NSInteger)section isOpen:(BOOL)isOpen{
    
}

-(void)viewDidClickWithSection:(NSInteger)section viewSelected:(BOOL)viewSelected{
    ((YBSelectHeadModel *)(self.headArray[section])).ISALLSELECT = viewSelected;
    
    for (YBPeopleInfoModel * model in self.dataArray) {
        model.ISSELECT = viewSelected;
        if (viewSelected) {
            if (self.isAddPeople) {
                [self.addPeopleDataSource ybAddObjectToArrayWithModel:model];
            }
            else{
                [self.myDataSource ybAddObjectToArrayWithModel:model];
            }
        }
        else{
            if (self.isAddPeople) {
                [self.addPeopleDataSource ybRemoveObjectFromArrayWithModel:model];
            }
            else{
                [self.myDataSource ybRemoveObjectFromArrayWithModel:model];
            }
        }
    }
    [self.tableView reloadData];
    [self mySelectArrayChanged];
}




-(void)mySelectArrayChanged{
    self.ybSelectChange = !self.ybSelectChange;
}

- (UIScrollView *)titleScrollView{
    if (!_titleScrollView ) {
        _titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, ItemHeight * 80)];
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        _titleScrollView.contentSize = _titleScrollView.size;
        _titleScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _titleScrollView;
    
}


-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, ItemHeight * 80, self.frame.size.width, self.frame.size.height - ItemHeight * 80) style:UITableViewStyleGrouped];
        [_tableView registerClass:[YBSelectPeopleNormalTableViewCell class] forCellReuseIdentifier:CELLID];
        [_tableView registerClass:[YBSelectDeptListTableViewCell class] forCellReuseIdentifier:DEPTID];
        [_tableView registerClass:[YBSelectPeopleHeadView class] forHeaderFooterViewReuseIdentifier:HEADER];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView adaptiveIOS11];
        
    }
    return _tableView;
}


-(void)loadDataWithUserArray:(NSArray *)userArray deptArray:(NSArray *)deptArray
{
    self.mainUserArray = userArray;
    self.mainDeptArray = deptArray;
    for (YBSelectHeadModel * model in self.mainDeptArray) {
        if ([model.FID isEqualToString:@"0"] || [model.FID isEqualToString:@""]) {
            model.NAME = @"全部";
            [self addHeadButtonWithHeadModel:model];
            break;
        }
    }
    [self ybRestructureDataSourceWithModel:self.selectHeadArray.lastObject];
}

-(void)ybRestructureDataSourceWithModel:(YBSelectHeadModel *)model{
    NSArray * idArray;
    if (self.isAddPeople) {
        idArray = [self.addPeopleDataSource getCurrentSelectIdArray];
    }
    else{
        idArray = [self.myDataSource getCurrentSelectIdArray];
    }
    [self.dataArray removeAllObjects];
    [self.headArray removeAllObjects];
    NSInteger selectCount = 0;
    for (YBSelectHeadModel * deptModel in self.mainDeptArray) {
        if ([deptModel.FID isEqualToString:model.ID]) {
            [self.dataArray addObject:deptModel];
        }
    }
    for (YBPeopleInfoModel * userModel in self.mainUserArray) {
        if ([userModel.FID isEqualToString:model.ID]) {
            if ([idArray containsObject:userModel.ID]) {
                userModel.ISSELECT = YES;
                selectCount ++;
            }
            else{
                userModel.ISSELECT = NO;
            }
            [self.dataArray addObject:userModel];
        }
    }
    NSInteger userCount = 0;
    for (YBSelectPeopleTotalModel * totalModel in self.dataArray) {
        if ([totalModel.DATA_TYPE integerValue] == 1) {
            userCount ++;
        }
    }
    if (self.dataArray.count > 0 && userCount == self.dataArray.count) {
        YBSelectHeadModel * headModel = [[YBSelectHeadModel alloc]init];
        headModel.ISOPEN = YES;
        headModel.NAME = @"全选";
        if (selectCount == self.dataArray.count) {
            headModel.ISALLSELECT = YES;
        }
        else{
            headModel.ISALLSELECT = NO;
        }
        [self.headArray addObject:headModel];
    }
    [self.tableView reloadData];
}


-(void)ybReloadData{
    NSArray * idArray;
    if (self.isAddPeople) {
        idArray = [self.addPeopleDataSource getCurrentSelectIdArray];
    }
    else{
        idArray = [self.myDataSource getCurrentSelectIdArray];
    }
    NSInteger selectedCount = 0;
    for (YBSelectPeopleTotalModel * tempModel in self.dataArray) {
        if ([tempModel.DATA_TYPE integerValue] == 1) {
            if ([idArray containsObject:tempModel.ID]) {
                selectedCount ++;
                ((YBPeopleInfoModel *)tempModel).ISSELECT = YES;
            }
            else{
                ((YBPeopleInfoModel *)tempModel).ISSELECT = NO;
            }
        }
    }
    if (self.headArray.count > 0) {
        YBSelectHeadModel * tempHeadModel = self.headArray[0];
        if (selectedCount == self.dataArray.count) {
            tempHeadModel.ISALLSELECT = YES;
        }
        else{
            tempHeadModel.ISALLSELECT = NO;
        }
    }
    [self.tableView reloadData];
}


-(YBSelectShareSingalData *)myDataSource
{
    if (!_myDataSource) {
        _myDataSource = [YBSelectShareSingalData getYBSelectShareSingalData];
    }
    return _myDataSource;
}


-(YBAddPeopleSignalData *)addPeopleDataSource
{
    if (!_addPeopleDataSource) {
        _addPeopleDataSource = [YBAddPeopleSignalData getYBSelectShareSingalData];
    }
    return _addPeopleDataSource;
}


-(NSMutableArray *)selectHeadArray
{
    if (!_selectHeadArray) {
        _selectHeadArray = [NSMutableArray array];
    }
    return _selectHeadArray;
}


-(NSMutableArray<UIButton *> *)headButtonArray
{
    if (!_headButtonArray) {
        _headButtonArray = [NSMutableArray array];
    }
    return _headButtonArray;
}

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


-(NSMutableArray *)headArray
{
    if (!_headArray) {
        _headArray = [NSMutableArray array];
    }
    return _headArray;
}


@end
